package com.chapter16.callable;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @author 宋鑫宇
 * @version 1.0
 * 通过实现 Callable 接口，重写call方法 ，封装要做的事情
 * 用 FutureTask 把 Callable 对象封装成线程任务对象
 */
public class Callable_ {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //2.创建 Callable 对象
        Callable<String> a = new A(100);
        //4.把 Callable 对象交给 FutureTask 对象,
        // FutureTask 是 Runnable 的子类，可以在线程执行完毕之后通过调用get方法得到线程执行完成的结果
        FutureTask<String> s = new FutureTask<>(a);
        Thread thread = new Thread(s);
        thread.start();
//        System.out.println(stringFutureTask.get());
        //计算1到200的和
        Callable<String> a1 = new A(200);
        FutureTask<String> s1 = new FutureTask<>(a1);
        Thread thread1 = new Thread(s1);
        thread1.start();

        System.out.println("1-100结果是："+s.get());
        System.out.println(thread.getState());
        System.out.println("1-200结果是："+s1.get());
    }
}

// 1.定义一个任务类 实现Callable接口
class A implements Callable<String> {
    private int n;

    public A(int n) {
        this.n = n;
    }

    @Override
    public String call() throws Exception {
        int sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += i;
        }
        return "结果是" + sum;
    }
}